import { violationStr } from './checkStr'
/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

export function arrayToObject(arr: any, defaultValue = '1') {
  return arr.reduce((obj: any, key: any) => {
    obj[key] = defaultValue;
    return obj;
  }, {});
}

//检测字符串里是否包含数组里的元素
export function containsAny(str: string, arr: string[]) {
  return arr.some(item => str.includes(item));
}

export function findMatchingElements(str: string, arr: string[]) {
  // 过滤出在字符串中存在的元素
  return arr.filter(item => str.includes(item));
}

export function highlightMatches(str: string, keywords: string[]) {
  // 按长度降序排序关键词（避免短关键词在长关键词内部重复匹配）
  const sortedKeywords = [...keywords].sort((a, b) => b.length - a.length);

  // 存储所有匹配位置和内容
  const matches: any = [];

  // 查找所有匹配项
  sortedKeywords.forEach(keyword => {
    let startIndex = 0;
    while (startIndex < str.length) {
      const index = str.indexOf(keyword, startIndex);
      if (index === -1) break;

      // 检查是否已被更长的关键词覆盖
      const isOverlapped = matches.some((match: any) =>
        index >= match.start && index < match.end
      );

      if (!isOverlapped) {
        matches.push({
          keyword,
          start: index,
          end: index + keyword.length
        });
      }

      startIndex = index + 1;
    }
  });

  // 如果没有匹配项，直接返回原字符串
  if (matches.length === 0) return str;

  // 按起始位置降序排序（从后向前处理，避免索引变化）
  matches.sort((a: any, b: any) => b.start - a.start);

  // 替换匹配项
  let result = str;
  matches.forEach((match: any) => {
    const before = result.substring(0, match.start);
    const matchedText = result.substring(match.start, match.end);
    const after = result.substring(match.end);

    result = `${before}<b style="color:red">${matchedText}</b>${after}`;
  });

  return result;
}

export function debounce(func: Function, delay: number): (...args: any[]) => void {
  let timer: ReturnType<typeof setTimeout> | null;
  return (...args: any[]) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

export function validateStringAllErrors(str: string) {
  const errors = [];

  if (!str || str.trim() === '') {
    errors.push("请输入内容");
  }

  //const forbiddenWords = ["医用", "医疗器械", "手术器械"];
  const foundWords = violationStr.filter(word => str.includes(word));
  if (foundWords.length > 0) {
    errors.push(`包含禁止词汇: ${foundWords.join(", ")}`);
  }

  if (str.length > 100) {
    errors.push(`长度超过100字 (${str.length})`);
  }

  const specialChars = str.match(/[#$￥%&*\/\\?|:;<>{}()[\]]/g);
  if (specialChars) {
    errors.push(`包含特殊字符: ${Array.from(new Set(specialChars)).join(", ")}`);
  }

  return errors.length > 0 ? errors : "内容验证通过";
}

export function countByValue(arr: any, targetValue: any) {
  return arr.filter((item: any) => item.value === targetValue).length;
}

export function convertWord(obj: any) {
  if (obj.length) {
    const labels = obj
      .filter((item: any) => item.value === 1 || item.value === 2)
      .map((item: any) => item.label);
    return labels.join('/').replace(/\/$/, '');
  } else {
    return ''
  }
}

export function generateAndCheckCombinations(str: string, arr1: string[], arr2: string[], forbiddenExample: string = '') {
  // 1. 生成所有组合
  const combinations = [];

  for (const prefix of arr1) {
    for (const suffix of arr2) {
      const combination = prefix + str + suffix;
      combinations.push(combination);
    }
  }

  // 2. 检查重复情况
  const result = {
    allCombinations: combinations,
    containsForbidden: combinations.includes(forbiddenExample),
    duplicates: findDuplicates(combinations),
    forbiddenExample: forbiddenExample
  };

  return result;
}
// 辅助函数：查找数组中的重复项
function findDuplicates(arr: string[]) {
  const seen = new Set();
  const duplicates = new Set();

  for (const item of arr) {
    if (seen.has(item)) {
      duplicates.add(item);
    } else {
      seen.add(item);
    }
  }

  return Array.from(duplicates);
}

//可以实现[前置+主词+后置]
export function generateCombinations(str: string, arr1: string[], arr2: string[]) {
  const result = [];

  for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
      result.push(`${arr1[i]}${str}${arr2[j]}`);
    }
  }

  return result;
}

//比较两个数组里有没有相同的项
export function hasCommonItem(arr1: any[], arr2: any[]): boolean {
  return arr1.some(item => arr2.includes(item));
}

//字符串转buffer
export function strToBuffer(s: string) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i < s.length; i++) {
    view[i] = s.charCodeAt(i) & 0xFF;
  }
  return buf;
}

//数字转化成w
export function numToW(num: number) {
  if (num < 10000) {
    return num;
  }

  const units = ['', 'w', '10w', '100w', '1000w'];
  let index = 0;
  while (num >= 10000) {
    num /= 10000;
    index++;
  }

  return num.toFixed(2) + units[index];
}

//检测数组中是否有重复的项
export function hasDuplicate(arr: any[]) {
  let filteredArray = arr.filter(item => item !== "")
  return new Set(filteredArray).size !== filteredArray.length
}

//检测数组中是否有指定项
export function hasItem(arr: any[], item: any) {
  return arr.some((i) => i === item);
}

//检测数组中的项是否包含指定字符串
export function hasItemWithString(arr: any[], str: string) {
  return arr.some((i) => i.includes(str));
}

//检测数组中每一项是否包含指定数组里的项
export function checkContains(a: any[], b: any[]) {
  if (!Array.isArray(a) || !Array.isArray(b)) {
    return [];
  }

  const setA = new Set(a);
  return b.map(itemB => {
    if (Array.isArray(itemB)) {
      return itemB.some(item => setA.has(item));
    }
    return false;
  });
}

//数组转字符串label+value ====> label/label
export function formatLabels(arr: any) {
  const validItems = arr.filter((item: any) => item.value > 0).map((item: any) => item.label);
  return validItems.length > 1 ? validItems.join('/') : validItems[0] || '';
}

export function getFreedomWordID(arr: any[]) {
  let ids: number[] = []
  arr.forEach(item => {
    if (item.State) {
      ids.push(item.ID)
    }
  })
  return ids
}

export function checkGeo(Geo: number) {
  let geo = {
    url: '',
    api: ''
  }
  if (Geo === 1) {
    geo.api = '/GEOApi';
    geo.url = '/geo';
  } else if (Geo === 2) {
    geo.api = '/GEOBasicApi';
    geo.url = '/geo-basic';
  }
  return geo;
}

export function checkMainWord(obj: any) {
  if (obj.length) {
    const labels = obj
      .filter((item: any) => item.value === 1)
      .map((item: any) => item.label);
    return labels.join('/').replace(/\/$/, '');
  } else {
    return ''
  }
}